package com.acdc.jobs;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.acdc.service.IIotModuleService;
import com.acdc.device.service.IMeterDeviceService;
import com.acdc.domain.IotModule;
import com.acdc.domain.IotModuleHeartbeat;
import com.acdc.device.domain.MeterDevice;
import com.acdc.business.domain.PowerConsumptionRecord;
import com.acdc.business.service.IPowerConsumptionRecordService;
import com.acdc.service.IElectricityMeterActivePowerService;
import java.util.List;
import java.util.Date;
import com.acdc.domain.ElectricityMeterActivePower;
import lombok.extern.slf4j.Slf4j;
import com.github.pagehelper.PageHelper;

@Slf4j
@Component("deviceOfflineJob")
public class DeviceOfflineJob {

    private static final int TIMEOUT = 120;

    @Autowired
    private IIotModuleService iotModuleService;

    @Autowired
    private IMeterDeviceService meterDeviceService;

    @Autowired
    private IPowerConsumptionRecordService powerConsumptionRecordService;

    @Autowired
    private IElectricityMeterActivePowerService electricityMeterActivePowerService;

    public void execute() {
        Date now = new Date();
        List<IotModule> iotModuleList = iotModuleService.selectIotModuleList(new IotModule());
        for (IotModule iotModule : iotModuleList) {
            IotModuleHeartbeat iotModuleHeartbeat = iotModuleService.selectLatestIotModuleHeartbeatByIotModuleId(iotModule.getId());
            List<MeterDevice> meterDeviceList = meterDeviceService.selectMeterDeviceByIotModuleId(iotModule.getId());
            // 如果心跳时间大于120秒，则认为设备离线
            if (iotModuleHeartbeat != null && iotModuleHeartbeat.getHeartbeatTime().getTime() < now.getTime() - TIMEOUT * 1000) {
                for (MeterDevice meterDevice : meterDeviceList) {
                    log.info("设备离线: {}", meterDevice.getLogicAddr());
                    meterDevice.setDeviceStatus("1");
                    meterDeviceService.updateMeterDevice(meterDevice);

                    terminateOrder(meterDevice);
                }
            } else {
                meterDeviceList.forEach(meterDevice -> {
                    if (meterDevice.getDeviceStatus().equals("3")) {
                        PowerConsumptionRecord query = new PowerConsumptionRecord();
                        query.setMeterId(meterDevice.getId());
                        query.setStatus(1L);
                        List<PowerConsumptionRecord> powerConsumptionRecordList = powerConsumptionRecordService.selectPowerConsumptionRecordList(query);
                        ElectricityMeterActivePower query1 = new ElectricityMeterActivePower();
                        query1.setElectricityMeterId(meterDevice.getId());
                        PageHelper.startPage(1, 10, null).setReasonable(false);
                        query1.setCollectionTime(powerConsumptionRecordList.get(0).getCreatedAt());
                        List<ElectricityMeterActivePower> electricityMeterActivePowerList = electricityMeterActivePowerService.selectElectricityMeterActivePowerList(query1);
                        // 判断第一条数据和最后一条数据的功率是否相同，如果相同，终止订单
                        if (electricityMeterActivePowerList.size() >= 10) {
                            Float firstPower = electricityMeterActivePowerList.get(0).getActivePower();
                            Float lastPower = electricityMeterActivePowerList.get(electricityMeterActivePowerList.size() - 1).getActivePower();
                            log.info("设备在使用中，第一条数据功率: {}, 最后一条数据功率: {}", firstPower, lastPower);
                            
                            if (firstPower.floatValue() - lastPower.floatValue() < 0.01) {
                                log.info("设备在使用中，但最新的有效功率时间超过10分钟未更新，终止订单: {}", meterDevice.getLogicAddr());
                                terminateOrder(meterDevice);
                            }
                        }
                    }
                });
            }
        }
    }

    private void terminateOrder(MeterDevice meterDevice) {
        // 查看设备是否在使用中，如果使用中离线终止订单
        PowerConsumptionRecord query = new PowerConsumptionRecord();
        query.setMeterId(meterDevice.getId());
        query.setStatus(1L);
        List<PowerConsumptionRecord> powerConsumptionRecordList = powerConsumptionRecordService.selectPowerConsumptionRecordList(query);
        if (powerConsumptionRecordList.size() > 0) {
            PowerConsumptionRecord powerConsumptionRecord = powerConsumptionRecordList.get(0);
            powerConsumptionRecordService.finish(powerConsumptionRecord.getId());
        }
    }
}
